﻿<?php
/**
 * @version		$Id: media.php 10381 2008-06-01 03:35:53Z pasamio $
 * @package		Joomla
 * @subpackage	Media
 * @copyright	Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
 * @license		GNU/GPL, see LICENSE.php
 * Joomla! is free software. This version may have been modified pursuant to the
 * GNU General Public License, and as distributed it includes or is derivative
 * of works licensed under the GNU General Public License or other free or open
 * source software licenses. See COPYRIGHT.php for copyright notices and
 * details.
 */

/**
 * @package		Joomla
 * @subpackage	Media
 */
class XlsHelper
{
    public function upload()
    {
        global $mainframe;

        $file 		= JRequest::getVar( 'Filedata', '', 'files', 'array' );
        $folder		= JRequest::getVar( 'folder', '', '', 'path' );
        $err		= null;

        // Set FTP credentials, if given
        jimport('joomla.client.helper');
        JClientHelper::setCredentialsFromRequest('ftp');

        // Make the filename safe
        jimport('joomla.filesystem.file');
        $file['name']	= JFile::makeSafe($file['name']);

        if (isset($file['name'])) {
            $filepath = JPath::clean(JPATH_COMPONENT.DS.helpers.DS.$folder.DS.strtolower($file['name']));

            if (!$this->canUpload( $file, $err )) {
                
                $mainframe->enqueueMessage(JText::_('Không thể upload file.Có thể do file phải là file excel hoặc định dạng sai!'));
                
                if ($return) {
                    $mainframe->redirect(base64_decode($return).'&folder='.$folder);
                }
                return;
            }
            if (JFile::exists($filepath)) {
                // REDIRECT
                $this->delete($filepath);
            }

            if (!JFile::upload($file['tmp_name'], $filepath)) {
                // REDIRECT
                $mainframe->enqueueMessage(JText::_(JText::_('Error. Unable to upload file')));
                if ($return) {
                    $mainframe->redirect(base64_decode($return).'&folder='.$folder);
                }
                return;
            } else {
                $mainframe->enqueueMessage(JText::_('Upload complete'));
                // REDIRECT
                if ($return) {
                    $mainframe->redirect(base64_decode($return).'&folder='.$folder);
                }
                return;
            }
        } else {
            $mainframe->redirect('index.php', 'Invalid Request', 'error');
        }
    }
    function readxls(){
        
        $this->upload();
        
		$file 	= JRequest::getVar( 'Filedata', '', 'files', 'array' );
        $folder	= JRequest::getVar( 'folder', '', '', 'path' );
		
        /* ****************************************** */
		
		require_once 'PHPExcel'.DS.'PHPExcel'.DS.'IOFactory.php';
		//$_SERVER["DOCUMENT_ROOT"].JURI::root(true).DS.
		$path_file = 'components'.DS.'com_sim'.DS.'helpers'.DS.$folder.DS.$file['name'];
		
		if (!file_exists($path_file)) {
			
			exit("File does not exist.");
		}
		
		$objPHPExcel = PHPExcel_IOFactory::load($path_file);
		$activeSheet = $objPHPExcel->getActiveSheet();
		$size = $objPHPExcel->getActiveSheet()->getHighestRow();
		$db = JFactory::getDbo();
		/* ****************************************** */        		
		for($i=2; $i<=$size; $i++)
		{
			$obj = new stdClass();
			$obj->sim_id = null;
			$obj->admin_id = 1;
			$obj->provider_id = 1;
			$obj->categori_id = 9;
			$obj->curency = "VNĐ";
			$obj->del_flag = 0;
			$obj->sim_numb = $activeSheet->getCell('A'.$i)->getValue();
			$obj->price    = $activeSheet->getCell('B'.$i)->getValue();
			date_default_timezone_set('Asia/Ho_Chi_Minh');
			$obj->last_update = date("Y-m-d H:i:s");
			if(substr($obj->sim_numb,0,1) != "0")
			$obj->sim_numb = "0".$obj->sim_numb;
			$db->insertObject('#__sim', $obj);
			//$simbatch[$i-2] = $obj;
			
		}
		
        $this->delete();
        global $mainframe;
		$mainframe->redirect('index.php?option=com_sim', 'Đã nhập sim vào database thành công');
		
		return true;
    
	}
	
    /**
     * Deletes paths from the current path
     *
     * @param string $listFolder The image directory to delete a file from
     * @since 1.5
     */
    function delete()
    {
        global $mainframe;
        $file 		= JRequest::getVar( 'Filedata', '', 'files', 'array' );
        $folder		= JRequest::getVar( 'folder', '', '', 'path' );
        // Set FTP credentials, if given
        jimport('joomla.client.helper');
        JClientHelper::setCredentialsFromRequest('ftp');

        // Initialize variables
        $ret = true;
        $fullPath = JPath::clean(JPATH_COMPONENT.DS.helpers.DS.$folder.DS.strtolower($file['name']));
        if (is_file($fullPath)) {
		
            $ret = !JFile::delete($fullPath);
			
        } else if (is_dir($fullPath)) {
		
            $files = JFolder::files($fullPath, '.', true);
            $canDelete = true;
            
			foreach ($files as $file) {
                if ($file != 'index.html') {
                    $canDelete = false;
                }
            }
            if ($canDelete) {
			
                $ret = !JFolder::delete($fullPath);
            } else {
			
                JError::raiseWarning(100, JText::_('Unable to delete:').$fullPath.' '.JText::_('Not Empty!'));
            }
			
        }
    }
	
    
	/**
     * Checks if the file can be uploaded
     *
     * @param array File information
     * @param string An error message to be returned
     * @return boolean
     */
    function canUpload( $file, &$err )
    {
        $params = &JComponentHelper::getParams( 'com_media' );

        if(empty($file['name'])) {
            $err = 'Please input a file for upload';
            return false;
        }

        jimport('joomla.filesystem.file');
        if ($file['name'] !== JFile::makesafe($file['name'])) {
            $err = 'WARNFILENAME';
            return false;
        }

        $format = strtolower(JFile::getExt($file['name']));
        if (!$format=='xls')
        {
            $err = 'WARNFILETYPE';
            return false;
        }

        $maxSize = (int) $params->get( 'upload_maxsize', 0 );
        if ($maxSize > 0 && (int) $file['size'] > $maxSize)
        {
            $err = 'WARNFILETOOLARGE';
            return false;
        }

        return true;
    }

    function parseSize($size)
    {
        if ($size < 1024) {
            return $size . ' bytes';
        }
        else
        {
            if ($size >= 1024 && $size < 1024 * 1024) {
                return sprintf('%01.2f', $size / 1024.0) . ' Kb';
            } else {
                return sprintf('%01.2f', $size / (1024.0 * 1024)) . ' Mb';
            }
        }
    }
}